<template>
  <div class="list-table-box">
    <!-- <div class="list-caption f16" style="padding-left: 12px">{{ tableTitle }}</div> -->
    <CommonTablePage
      ref="themeTable"
      :loading="tableLoading"
      :current="formData.pageNo"
      :columns="columns"
      :tableData="tableData"
      :total="pagination.total"
      @on-selection-change="handleTableSelect"
      @on-sort-change="handleTableSort"
      @on-change="handlePageChange"
      @on-page-size-change="handlePageSizeChange"
    ></CommonTablePage>
  </div>
</template>

<script>
import CommonTablePage from '@/components/common/CommonTablePage/CommonTablePage'
// util
import { createCommonPagination } from '@/utils/service.js'
import { createColumns } from './service/themePublicity'
import $bus from '@/utils/bus.js'
import { cloneDeep, attachmenDownload } from '@/utils/uitls.js'

import {
  getCommandDetail_list,
  getCommandDetail_list_update,
  postCommandDetail_list_delete,
  postCommandDetail_list_export,
} from '@/api/manageEnd/propagandizeDirective/allDirective'
export default {
  name: 'ThemePublicitySituation',

  components: { CommonTablePage },

  props: {
    formData: { type: Object },
  },

  data() {
    return {
      isInit: false,
      tableLoading: false,
      allData: {},
      columns: [],
      tableData: [],
      selection: [],
      orderField: '',
      orderDesc: true,
      pagination: createCommonPagination(),
    }
  },

  computed: {
    id() {
      return this.$route.query.id
    },

    tableTitle() {
      return this.allData.title || ''
    },
  },

  methods: {
    handleFormSubmit(params, no_reset) {
      if (no_reset !== true) {
        params.pageNo = 1
      }
      const p = { ...params }
      p.desc = this.orderDesc
      p.orderField = this.orderField
      // console.log('handleFormSubmit', p)
      this.getCommandDetail_list(p)
    },

    handleTableSelect(selection) {
      this.selection = selection
    },

    handleTableSort({ column, key, order }) {
      // console.log(123, column, key, order)
      if (order === 'normal') return
      this.orderDesc = order === 'desc'
      this.orderField = key
      this.handleFormSubmit(this.formData)
    },

    handlePageChange(page) {
      this.formData.pageNo = page
      this.handleFormSubmit(this.formData, true)
    },
    handlePageSizeChange(pageSize) {
      this.formData.pageSize = pageSize
      this.handleFormSubmit(this.formData, true)
    },

    handleEditTableRow(row) {
      // console.log(row)
      // return
      const content = {}
      Object.entries(row).forEach(([k, v]) => {
        if (k.includes('backup')) {
          const a = k.split('_')
          content[a[1]] = v
        }
      })
      const params = {
        detailId: row.detailId,
        content,
      }
      // console.log('params', params)
      this.getCommandDetail_list_update([params])
      // 表格的双向绑定数据保存在子组件中
      // const data = this.$refs['themeTable'].$children[0].data
      // const data = this.$refs['themeTable'].$children[0].$children[0].data
      // console.log('data', data)
      // row.editable = !row.editable
      // console.log(this.$refs['themeTable'].$children[0])
    },

    handleDeleteTableRow(row) {
      // console.log(row)
      this.postCommandDetail_list_delete({ ids: row.detailId })
    },

    handleExport(params) {
      // console.log('handleExport', params)
      const msg = params.msg
      const allData = cloneDeep(this.allData)
      if (msg !== 'all') {
        if (!this.selection.length) return
        // console.log(this.selection)
        allData.data = this.selection
      }
      this.postCommandDetail_list_export(allData)
    },

    /* 编辑 */
    async getCommandDetail_list_update(data) {
      const res = await getCommandDetail_list_update(data)
      const status = res.data.status
      if (status === 0) {
        this.$Message.success('编辑成功')
        this.handleFormSubmit(this.formData)
      } else {
        this.$Message.error(res.data.message || '编辑失败')
      }
    },

    /* 删除 */
    async postCommandDetail_list_delete(params) {
      const res = await postCommandDetail_list_delete(params)
      const status = res.data.status
      if (status === 0) {
        this.$Message.success('删除成功')
        this.handleFormSubmit(this.formData)
      } else {
        this.$Message.error(res.data.message || '删除失败')
      }
    },

    /* 导出 */
    async postCommandDetail_list_export(data) {
      const res = await postCommandDetail_list_export(data)
      const status = res.data.status
      if (status === 0) {
        const data = res.data.data
        attachmenDownload(data)
      } else {
        this.$Message.error(res.data.message || '导出失败')
      }
    },

    /* 获取列表 */
    async getCommandDetail_list(params) {
      this.tableLoading = true
      const res = await getCommandDetail_list(this.id, params)
      // console.log('getCommandDetail_list', res)
      const data = res.data.data || {}
      this.allData = Object.freeze(data)
      this.tableData = (data.data || []).map((it) => ({
        ...it,
        editable: false,
      }))

      this.pagination.total = data.count || 0
      this.tableLoading = false

      if (!this.isInit) {
        this.$emit('on-update-title', this.allData.title || '')
        const { columns = [], sortField } = data
        this.columns = createColumns(this)
        const _columns = this.getColumns(columns, sortField)
        this.columns.splice(2, 0, ..._columns)
      }

      this.$nextTick(() => (this.isInit = true))
    },

    getColumns(columns, sortField) {
      const pushColumns = []

      const excludes = ['title', 'target', 'url'] // rank 上榜情况
      columns.forEach((c) => {
        const _c = {
          title: c.name,
          key: c.field,
          align: 'center',
          sortType: sortField === c.field ? 'desc' : '',
          sortable: c.sortable ? 'custom' : '',
          render: (h, params) => {
            const content = params.row.content || {}
            const key = params.column.key

            if (!excludes.includes(key) && params.row.editable) {
              if (!params.row['backup_' + key]) params.row['backup_' + key] = Number(content[key])
              return (
                // <i-input
                //   type="number"
                //   value={params.row['backup_' + key]}
                //   on-input={(val) => {
                //     console.log('val', val)
                //     if (val < 0) return params.row['backup_' + key] = params.row['backup_' + key]
                //     params.row['backup_' + key] = val
                //   }}
                // ></i-input>
                <input-number
                  value={params.row['backup_' + key]}
                  on-input={(val) => (params.row['backup_' + key] = val)}
                  min={0}
                  parser={(n) => {
                    if (Number(n) < 0) return '0'
                    return n
                  }}
                ></input-number>
              )
            } else {
              return h('span', content[key])
            }
          },
        }
        pushColumns.push(_c)
      })

      return pushColumns
    },
  },

  mounted() {
    this.handleFormSubmit(this.formData)
    $bus.$on('on-directive-reship-details', this.handleFormSubmit)
    $bus.$on('on-directive-export', this.handleExport)
  },

  beforeDestroy() {
    $bus.$off()
  },
}
</script>

<style lang="less" scoped></style>
